import { ref } from "vue";
import { RouteRecordRaw } from "vue-router";
import router from ".";
import _ from "lodash-es";

/**
 * 所有路由
 */
const allRoutes: RouteRecordRaw[] = [];

/**
 * 引入所有模块的路由
 */
const modules: Record<string, any> = import.meta.glob(
  ["@/router/modules/**/*.ts"],
  {
    eager: true,
  }
);

/**
 * 合并所有路由
 */
Object.keys(modules).forEach((key) => {
  allRoutes.push(...modules[key].default);
});

/**
 * 分组路由 分为静态路由 和动态路由
 * @param routes 需要分组的路由
 * @returns 路由信息
 */
function filterRouters(routes: RouteRecordRaw[]): {
  dynamicsRoutes: RouteRecordRaw[];
  staticRoutes: RouteRecordRaw[];
} {
  const tmpDynamicsRoutes: RouteRecordRaw[] = [];
  const tmpStaticRoutes: RouteRecordRaw[] = [];
  routes.map((route) => {
    const isStatic = route.meta?.static ?? true;

    const children = route.children ?? [];
    const { dynamicsRoutes, staticRoutes } = filterRouters(children);
    if (isStatic) {
      tmpStaticRoutes.push({
        ...route,
        children: staticRoutes,
      });
    } else {
      tmpDynamicsRoutes.push({
        ...route,
        children: dynamicsRoutes,
      });
    }
  });
  return {
    dynamicsRoutes: tmpDynamicsRoutes,
    staticRoutes: tmpStaticRoutes,
  };
}

const { dynamicsRoutes, staticRoutes } = filterRouters(allRoutes);

export function useDynamicsRoutesHook() {
  const isLoad = ref(false);
  const loadedRoues = ref<Array<() => void>>([]);

  // 加载动态路由
  const loadRoutes = () => {
    if (isLoad.value) {
      return;
    }
    dynamicsRoutes.map((route) => {
      loadedRoues.value.push(router.addRoute(route));
    });
    isLoad.value = true;
  };

  // 移除动态路由
  const removeRoutes = () => {
    loadedRoues.value.map((call) => {
      call();
    });
    loadedRoues.value = [];
    isLoad.value = false;
  };
  return {
    isLoad,
    loadRoutes,
    loadedRoues,
    removeRoutes,
  };
}

export { allRoutes, dynamicsRoutes, staticRoutes };
